package com.example.blog_system_ssm.service;

import com.example.blog_system_ssm.common.Constant;
import com.example.blog_system_ssm.common.SnowFlakeUtils;
import com.example.blog_system_ssm.component.RedisUtil;
import com.example.blog_system_ssm.mapper.ArticleMapper;
import com.example.blog_system_ssm.model.ArticleInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private RedisUtil redisUtil;
    public List<ArticleInfo> getMyList(Long uid,Integer psize,Integer offset) {
        return articleMapper.getMyList(uid,psize,offset);
    }

    //初始化一个雪花算法工具类，设置机房ID和机器ID都为0
    SnowFlakeUtils snowFlakeUtils=new SnowFlakeUtils(0,0);

    @Transactional
    //确保事务原子性
    public int delete(Long aid,Long uid){
        //先操作数据库，再删除缓存
        int result=articleMapper.delete(aid, uid);
        //更新文章总数
        articleMapper.incrArticleCount(uid,-1);
        redisTemplate.delete(Constant.CACHE_ARTICLE_KEY+aid);
        return result;
    }

    public ArticleInfo getDetail(Long aid){
        //解决缓存穿透和击穿问题
        return redisUtil.queryWithMutex(Constant.CACHE_ARTICLE_KEY,aid,ArticleInfo.class,articleMapper::getDetail,
                Constant.CACHE_ARTICLE_TTL, TimeUnit.MINUTES);
    }

    @Transactional
    //确保事务原子性
    public int update(Long aid, Long uid, String title, String content) {
        //先操作数据库，再删除缓存
        int result=articleMapper.update(aid, uid, title, content);
        redisTemplate.delete(Constant.CACHE_ARTICLE_KEY+aid);
        return result;
    }

    @Transactional
    //确保事务原子性,插入失败则回滚
    public int add(Long uid,String title,String content){
        //更新文章总数
        articleMapper.incrArticleCount(uid,1);
        //文章本身就不存在缓存所以不需要删除
        return articleMapper.add(uid, snowFlakeUtils.nextId(), title,content);
    }

    public int getTotalCount() {
        return articleMapper.getTotalCount();
    }
    public int getMyTotalCount(Long uid) {
        return articleMapper.getMyTotalCount(uid);
    }

    //分页
    public List<ArticleInfo> getList(Integer psize,Integer offset){
        return articleMapper.getList(psize,offset);
    }

    public List<Long> getAllId(){return articleMapper.getAllId();}
    public int incrNumById(Long aid,Integer incr){
        return articleMapper.incrNumById(aid, incr);
    }
}
